package com.coollang.smartbra.fragment;

import android.content.Context;
import android.graphics.Color;
import android.graphics.Typeface;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.coollang.smartbra.R;
import com.coollang.smartbra.activity.ActionActivity;
import com.coollang.smartbra.adapter.PbzcFragmentAdapter;
import com.coollang.smartbra.base.ActionFragment;
import com.coollang.smartbra.base.MyApplication;
import com.coollang.smartbra.beans.ActionData;
import com.coollang.smartbra.utils.ActivitySwitcher;
import com.coollang.smartbra.utils.PbzcTimeUtils;
import com.coollang.smartbra.utils.TimeUtils;
import com.coollang.smartbra.utils.UIUtils;
import com.coollang.smartbra.views.CircularSeekBarBcg;
import com.coollang.smartbra.views.CountView;
import com.nineoldandroids.view.ViewHelper;

import java.util.ArrayList;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

/**
 * @Auther: Timmy
 * @Data: 2017/5/12
 * @Fuction: 平板支撑的Fragment
 */

public class PbzcFragment extends ActionFragment {
    private static final String TAG = PbzcFragment.class.getSimpleName();

    @BindView(R.id.btn_start)
    Button mBtnStart;
    @BindView(R.id.circle_seekbar)
    CircularSeekBarBcg mCircularSeekBar;
    @BindView(R.id.nub_stop)
    TextView nubStop;
    @BindView(R.id.tv_lock)
    TextView tvLock;
    @BindView(R.id.tv_next)
    TextView tvNext;
    @BindView(R.id.tv_second)
    TextView tvSecond;
    @BindView(R.id.tv_tips)
    TextView tvTips;
    @BindView(R.id.tv_heart_rate)
    CountView tvHeartRate;
    @BindView(R.id.pbzc_listview)
    ListView mListView;
    @BindView(R.id.ll_action_tv)
    RelativeLayout mRLActionTv;
    @BindView(R.id.ll_listview)
    LinearLayout mLlListView;
    @BindView(R.id.tv_u_money)
    CountView tvUMoney;
    Unbinder unbinder;

    private ArrayList<ActionData> mActionDatas;

    // 今日U币
    @BindView(R.id.tv_today_umoney)
    TextView mTvTodayUmoney;

    private View mView;
    private Context mContext;
    private Timer timer;
    private TimerTask task;
    private int progress;
    private PbzcFragmentAdapter mAdapter;
    private PbzcTimeUtils mPbzcTimeUtils;

    @Override
    protected View inflateView(LayoutInflater inflater) {
        mView = inflater.inflate(R.layout.fragment_pbzc, null, false);
        mContext = getContext();
        unbinder = ButterKnife.bind(this, mView);
        return mView;
    }

    @Override
    protected void initView(View view) {
        mCircularSeekBar.setMaxProgress(1000);
        // 将下一项隐藏掉
        tvNext.setVisibility(View.INVISIBLE);
        initLongClick();//长按结束
        initLongClickLock();

        Typeface typeFace = Typeface.createFromAsset(getActivity().getAssets(), "fonts/enfragment_type.ttf");
        //设置字体
        tvSecond.setTypeface(typeFace);

        // 设置ListView
        mAdapter = new PbzcFragmentAdapter(mContext);
        mListView.setAdapter(mAdapter);
    }

    @Override
    protected void initData() {
        mPbzcTimeUtils = new PbzcTimeUtils();
        mActionDatas = new ArrayList<>();
    }

    @OnClick({R.id.btn_start, R.id.nub_stop, R.id.tv_action_details})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_start:
                ActivitySwitcher.goCountTimeAct(getActivity(), mBtnStart);
                break;
            case R.id.nub_stop:
                break;
            case R.id.tv_action_details:
                ArrayList<Integer> data = mAdapter.getData();
                ArrayList<ActionData> actionData = mAdapter.getActionData();
                ActivitySwitcher.goToActionDetails(getActivity(), data, actionData);
                break;
        }
    }


    @Override
    public void onResume() {
        super.onResume();
        continueAction();
    }

    @Override
    public void onPause() {
        super.onPause();

        mPbzcTimeUtils.setPause_totalTime(true);
        mPbzcTimeUtils.setPause_deputyTime(true);

    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
        handler.removeCallbacksAndMessages(null);
        mPbzcTimeUtils.stopTimer();
    }

    @Override
    public void showLockTV() {
        mCircularSeekBar.setProgressColor(Color.parseColor("#4DF79444"));
        nubStop.setVisibility(View.VISIBLE);
        tvLock.setVisibility(View.GONE);
    }

    @Override
    public void showStopTV() {
        mCircularSeekBar.setProgressColor(Color.parseColor("#4DF79444"));
        nubStop.setVisibility(View.VISIBLE);
        tvLock.setVisibility(View.GONE);
    }

    @Override
    public void startAction() {
        mBtnStart.setVisibility(View.GONE);
        nubStop.setVisibility(View.VISIBLE);
        mRLActionTv.setVisibility(View.VISIBLE);
        mLlListView.setVisibility(View.VISIBLE);

        mTvTodayUmoney.setText("本次运动U币");
        tvUMoney.setText("0");
        tvUMoney.setTextSize(23);

        mPbzcTimeUtils.setTimeListener(mTimeListener);

        // 清空动作数据
        mActionDatas.clear();
    }

    // 正确的时间
    private int ACTION_CORRECT = 0;

    @Override
    public void onPBZCRecieved(int heartRate, int errorFlag, int errorType) {
        setHeartRate(heartRate);

        if (errorFlag == 3) {
            return;
        }

        ActionData data = new ActionData();
        data.setActionType(6);
        data.setErrorFlag(errorFlag);
        data.setErrorType(((ActionActivity) mContext).getErrorType(errorType));
        data.setErrorInfo(((ActionActivity) mContext).getErrorInfo(errorType));
        data.setErrorVideo(((ActionActivity) mContext).getErrorVideo(errorType));

        mAdapter.addData(time, data);

        if (errorFlag == 1) {
            //正确
            mPbzcTimeUtils.setPause_deputyTime(false);
        } else if (errorFlag == 2) {
            // 错误
            mPbzcTimeUtils.setPause_deputyTime(true);
        }

        // 当为1 的时候 开始计时
        if (time == 0) {
            mPbzcTimeUtils.initTime();
        }
    }

    private void setHeartRate(int heartRate) {
        // 实现平板支撑

        if (Integer.parseInt(MyApplication.mLogInDataBean.getIsalarm()) == 1) {
            if (heartRate >= Integer.parseInt(MyApplication.mLogInDataBean.getHr_alarm())) {
                tvHeartRate.startAnimation(AnimationUtils.loadAnimation(mContext, R.anim.anim_alpha));
                tvHeartRate.setTextColor(UIUtils.getColor(R.color.barrey_20));
            } else {
                tvHeartRate.clearAnimation();
                tvHeartRate.setTextColor(UIUtils.getColor(R.color.black));
            }
        }

        tvHeartRate.setText(heartRate + "");
        tvHeartRate.setTextSize(23);
    }

    private int time = 0;

    PbzcTimeUtils.TimeListener mTimeListener = new PbzcTimeUtils.TimeListener() {
        @Override
        public void onTimeChange(long totalCurrTime, long deputyCurrTime) {

            // 返回的时间
            ACTION_CORRECT = (int) deputyCurrTime;
            time = (int) totalCurrTime;

            tvSecond.setText(TimeUtils.getFormatmillisecond(deputyCurrTime));
            mAdapter.upData((int) totalCurrTime);

            long l = (deputyCurrTime / 10000) * 60;

            tvUMoney.setText(l + "");

            if (deputyCurrTime < 11000) {
                // 倒计时10s 渐变隐藏
                ViewHelper.setAlpha(tvTips, (float) 1.0 - (deputyCurrTime / 1000) / (float) 10);
            }
        }
    };

    @Override
    public View getLockView() {
        return tvLock;
    }

    private void initLongClick() {
        nubStop.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        nubStopPressed(R.drawable.shape_yellow_cbg, getResources().getColor(R.color.white));
                        startCount();
                        break;
                    case MotionEvent.ACTION_UP:
                        if (progress >= 1000) {
                            setCircularSeekBarProgress(progress);
                            handler.removeCallbacksAndMessages(null);
                            // mPbzcTimeUtils.stopTimer();
                            // 在这里应该调用的是暂停指令,而不是停止时间的指令

                            mPbzcTimeUtils.setPause_totalTime(true);
                            mPbzcTimeUtils.setPause_deputyTime(true);

                            ((ActionActivity) mContext).toFinish(ACTION_CORRECT);
                        } else {
                            nubStopPressed(R.drawable.shape_cbg, getResources().getColor(R.color.progrss_bg));
                        }
                        task.cancel();
                        progress = 0;
                        setCircularSeekBarProgress(0);
                        break;
                    default:
                }
                return true;
            }
        });
    }

    @Override
    public void continueAction() {
        mPbzcTimeUtils.setPause_totalTime(false);
        mPbzcTimeUtils.setPause_deputyTime(false);
    }

    private void initLongClickLock() {
        tvLock.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        startCount();
                        break;
                    case MotionEvent.ACTION_UP:
                        if (progress >= 1000) {
                            setCircularSeekBarProgress(progress);
                            showStopTV();
                        }
                        task.cancel();
                        progress = 0;
                        setCircularSeekBarProgress(0);
                        break;
                }
                return true;
            }
        });
    }

    private void nubStopPressed(int shape_yellow_cbg, int color) {
        nubStop.setBackgroundResource(shape_yellow_cbg);
        nubStop.setTextColor(color);
    }

    private void startCount() {
        timer = new Timer();
        task = new TimerTask() {
            @Override
            public void run() {
                // 需要做的事:发送消息
                progress += 10;
                handler.sendEmptyMessage(1);
            }
        };
        timer.schedule(task, 0, 10);
    }

    Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    if (progress > 1000) {
                        task.cancel();
                    } else {
                        setCircularSeekBarProgress(progress);
                    }
            }
        }
    };

    private void setCircularSeekBarProgress(int progress) {
        mCircularSeekBar.setProgress(progress);
        mCircularSeekBar.invalidate();
    }
}
